import axios from 'axios'
import { createDiscreteApi } from 'naive-ui'
import { useCountStore, useSessionStore } from '@/stores'
import { useRouter } from 'vue-router'
const { message } = createDiscreteApi(
  ['message']
)
const router = useRouter()
export const baseURL = 'http://127.0.0.1:8080'
const _axios = axios.create({
	baseURL: baseURL
})
_axios.interceptors.request.use(config => {
	/* const token = VueCookie.get('sessionId')
	if (token) {
		config.headers.token = token
	} */
	return config
})
export const request = (url, method, data, callback) => {
	const sessionStore = useSessionStore();
	const axios_config = {
		url,
		method,
		headers: {
			token: sessionStore.sessionId
		}
	}
	if (method === 'post') {
		const formData = new FormData()
		for (const key in data) {
			if (data[key] instanceof Array) {
				for (const i in data[key]) {
					formData.append(key, data[key][i])
				}
			} else {
				formData.append(key, data[key])
			}
		}
		axios_config.data = formData
	} else {
		axios_config.params = data
	}
	const countStore = useCountStore()
	countStore.addCount()
	_axios.request(axios_config).then(response => {

		if (response.data.code === 200) {
			if (response.data.message) {
				message.success(response.data.message)
			}
			callback(response.data.content)
		} else {
			message.error(response.data.message, { duration: 10000 })
			if (response.data.code === 401) {
				router.push('/login')
			}
		}
	}).catch(error => {
		message.error(error.message)
	}).finally(() => {
		countStore.minusCount()
	})
}
export const get = (url, data, callback) => { request(url, 'get', data, callback) }
export const post = (url, data , callback, formObj = null) => {
	if (formObj) {
		formObj.validate(errors => {
			if (!errors) {
				request(url, 'post', data, callback)
			}
		})
	} else {
		request(url, 'post', data, callback)
	}
}